﻿function log(msg) {
	var logger = Components.classes["@mozilla.org/consoleservice;1"]
			.getService(Components.interfaces.nsIConsoleService);
	logger.logStringMessage("picbrowser:" + msg);
}

var picbrowser = new function() {
	const url404='ProfD/extensions/picbrowser@iodragon.com/chrome/content/image/404';
	var _browserJs;
	var _galleria;
	var _picList = new Array();
	var _pref;
	var _isShowState = true;
    var _strings;
	
	//----------------------------start
	var _piclocationid='';
	//----------------------------end

	var isfirstrun = function() {
		if (!_pref.getBoolPref("firstrun")) {
			_pref.setBoolPref("firstrun", true);
			return true;
		}
		return false;
	}
	var zoom = function(fator) {
		var img = _galleria.getActiveImage();
		if (!fator)
			fator = 0;

		if (fator == 0) {
			img.width = img.naturalWidth;
			img.height = img.naturalHeight;
		} else {
			img.width += fator * (img.naturalWidth);
			img.height += fator * (img.naturalHeight);
		}
	}
	var resize1 = function() {
		var img = _galleria.getActiveImage();
		var pWidth = _galleria.get("stage").clientWidth;
		var pHeight = _galleria.get("stage").clientHeight;
		var iRatio = img.width / img.height;

		if ( pWidth / pHeight > iRatio) {
			img.width = Math.floor(iRatio * pHeight);
			img.height = pHeight;
		} else {
			img.width = pWidth;
			img.height = Math.floor(pWidth / iRatio);
		}
	}
	var resize2 = function() {
		var img = _galleria.getActiveImage();
		var pWidth = _galleria.get("stage").clientWidth;
		var pHeight = _galleria.get("stage").clientHeight;
		var iWidth = img.height;
		var iHeight = img.width;
		var iRatio = iWidth / iHeight;

		if ( pWidth / pHeight > iRatio) {
			img.height = Math.floor(iRatio * pHeight);
			img.width = pHeight;
		} else {
			img.height = pWidth;
			img.width = Math.floor(pWidth / iRatio);
		}
	}
	var resize = resize1;
	var reposition = function(callback, option) {
		var img = _galleria.getActiveImage();
		// 计算中心点位置
		var cw = _galleria.get("stage").clientWidth / 2;
		var ch = _galleria.get("stage").clientHeight / 2;

		callback(option);

		// 重新定位
		img.style.top = Math.floor(ch - img.height / 2) + "px";
		img.style.left = Math.floor(cw - img.width / 2) + "px";
		// 更新状态栏信息
		showState(getPicState(img));
	}

	var showState = function(msgs) {
		var state;
		if(!_isShowState) return;
		
		if (msgs instanceof Array) {
			state = '';
			for (msg in msgs) {
				state += msgs[msg] + ' ';
			}
		} else {
			state = msgs;
		}
		document.getElementById('stateBox').textContent = state;
	}
	var getPicState = function(img) {
		var info = new Array();
		info['index'] = (_galleria.getIndex()) + 1 + '/' + _picList.length;
		info['resolution'] = img.naturalWidth + 'x' + img.naturalHeight;
		info['zoom'] = Math.floor(img.width * 100 / img.naturalWidth) + '%';
		info['size'] = Math.floor(_picList[_galleria.getIndex()].size / 1024)
				+ 'KB';
		return info;
	}
	var showNotFound = function(){
		var path=_pref.getCharPref("lastfolder");
		openFolder(url404,true);
		document.getElementById(_piclocationid).value = decodeURI(path);
		_pref.setCharPref("lastfolder",path);
	}
	var openFolder = function(path, isSysDir) {//alert("in");
		var path;//alert(path);
		if (!path) {
			var folder = sdk.file.selectFolder();
			if (!folder) {
				// 取消操作
				return;
			}
			path = folder.path;
		} else if (isSysDir) {
			var subdir=false;
			var pos = path.indexOf('/');
			if(pos > -1){
				subdir = path.substring(pos+1,path.length);
				path = path.substring(0,pos);
			}//alert("3");
			var folder = sdk.file.getSpecialFile(path,subdir);
			path = folder.path;
		} else if (!sdk.file.isFileExists(path)) {
			// 输入有误
			return false;
		}//alert("in2");
		document.getElementById(_piclocationid).value = path;
		//保存本次浏览目录
		_pref.setCharPref("lastfolder",encodeURI(path));
		//读取文件
		var fileArray = sdk.file.getFilesByFolder(path, "jpg,gif,png,bmp");
		//判断文件夹是否为空
		if(fileArray.length==0){
			showNotFound();
			return;
		}
		//判断是否要隐藏状态栏
		if(path==url404){
			_isShowState =false;
		}else{
			_isShowState =true;
		}
		delete _picList;
		_picList = new Array();
		for (var i = 0; i < fileArray.length; i++) {
			_picList.push({
						image : sdk.file.localPathToFilePath(fileArray[i].path),
						size : fileArray[i].fileSize
					});
		}
		_browserJs.$("<div/>").replaceAll(_browserJs.$('#galleria')).attr('id',
				'galleria').galleria({
					data_source : _picList
				});
		_browserJs.Galleria.get().shift(1);
		_galleria = _browserJs.Galleria.get(0);
		_galleria.bind(_browserJs.Galleria.IMAGE, function(e) {
					showState(getPicState(e.imageTarget));
				});
	};
	var setToolbarButton = function(){
		// 代码修改自火狐捷径
		var firefoxnav = document.getElementById("nav-bar"); // use "nav-bar"
																// in Firefox 2
																// and earlier
		var curSet = firefoxnav.currentSet;
		if (curSet.indexOf("picbIO") == -1) {
			var set;
			// Place the button before the urlbar
			if (curSet.indexOf("urlbar-container") != -1) {
				set = curSet.replace(/urlbar-container/,
						"picbIO,urlbar-container");// alert("1");
			} else // at the end
			{
				set = firefoxnav.currentSet + ",picbIO";// alert("2");
			}
			// alert(set);
			firefoxnav.setAttribute("currentset", set);
			firefoxnav.currentSet = set;
			document.persist("nav-bar", "currentset");
			// If you don't do the following call, funny things happen
			try {
				BrowserToolboxCustomizeDone(true);
			} catch (e) {
			}
		}
	}
	this.init = function() {
		_pref =  Components.classes["@mozilla.org/preferences-service;1"].
                    getService(Components.interfaces.nsIPrefService);
		_pref = _pref.getBranch("extensions.picbrowser@iodragon.com.");
		
		if(isfirstrun()){
			setToolbarButton();
		}
		_strings = document.getElementById("picbrowser-strings");
        
		_browserJs = document.getElementById('imgObj').contentWindow.wrappedJSObject;
		_galleria = _browserJs.Galleria.get(0);
		_galleria.bind(_browserJs.Galleria.IMAGE, function(e) {
					showState(getPicState(e.imageTarget));
				});
		//--------------------------------------start
		var interfaceVersion=_pref.getCharPref("interfaceVersion");
		if(interfaceVersion=='040')_piclocationid='piclocation';//imgUrl
		else if(interfaceVersion=='042')_piclocationid='piclocation';
		//--------------------------------------end
		
		
		//打开默认目录
		var tmp=_pref.getCharPref("lastfolder");
		openFolder('ProfD/extensions/picbrowser@iodragon.com/chrome/content/image',true);
		_pref.setCharPref("lastfolder",tmp);
		document.getElementById(_piclocationid).value = "";
	}
	this.play = function(option) {
		if (option < 0) {
			_galleria.pause();
		} else {
			_galleria.play(option * 1000);
		}
	}
	this.nextPic = function() {
		_galleria.next();
	}
	this.prevPic = function() {
		_galleria.prev();
	}
	this.rotate = function(degree) {
		var img = _galleria.getActiveImage();
		var rotateCss = _galleria.getActiveImage().style.MozTransform;
		olddgree = 0;
		if (rotateCss) {
			var r = /rotate\(([-]?[0-9]*)deg\)/;
			olddgree = r.exec(rotateCss);
			olddgree = parseInt(olddgree[1]);
		}
		rotateCss = "rotate(" + (degree + olddgree) + "deg)";
		img.style.MozTransform = rotateCss;
		// 修正旋转后图片超出显示区域

		if (olddgree % 180 == 0) {
			resize = resize2;
		}else{
			resize = resize1;
		}
		reposition(resize);
		// 更新状态栏信息
		showState(getPicState(img));
	}
	this.zoom = function(fator) {
		reposition(zoom, fator);
	}
	this.autosize = function() {
		reposition(resize);
	}
	this.openFolder = openFolder
	this.goto = function() {
		var path = document.getElementById(_piclocationid).value;
		if (path) {//alert("2");
			result = openFolder(path,true);//alert("1");
			if (result == false) {
				showState(_strings.getString("openFailedMsg"));
			}
		}
	}
	this.remove = function() {
		var file = _picList[_galleria.getIndex()].image;
		if (confirm(_strings.getString("deleteConfirmMsg"))) {
			sdk.file.removeFile(file);
			_galleria.next();
		}
	}
	this.setbg = function() {
		var kDesktopBackgroundURL = "chrome://browser/content/setDesktopBackground.xul";
		var img = _galleria.getActiveImage();
		openDialog(kDesktopBackgroundURL, "",
				"centerscreen,chrome,dialog,modal,dependent", img);
	}
	this.loadLast = function(){
		var path=_pref.getCharPref("lastfolder");
		openFolder(decodeURI(path));
	}

}

function slideM_toggle() {

	var itemTemp = document.getElementById("slideM_pic");
	var itemTemp2 = document.getElementById("slideM");

	var itemTemp3 = document.getElementById("slideM_arr");

	if (itemTemp.src == "pic/monitor.png") {
		itemTemp.src = "pic/monitor2.png";
		// itemTemp3.src="pic/arrow-up-dis.gif";
		picbrowser.play(-1);
	} else {
		itemTemp.src = "pic/monitor.png";// alert(itemTemp2.disabled);
		// itemTemp3.src="pic/arrow-up-hov.gif";
		picbrowser.play();
	}
	itemTemp2.disabled = !itemTemp2.disabled;

}
